package com.tarry.io.file.archive;

import cn.hutool.core.io.file.FileNameUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Objects;
import java.util.concurrent.LinkedBlockingQueue;

@Slf4j
public class ListFileProducer implements Runnable{

    private volatile LinkedBlockingQueue<FileInfo> fileInfoQueue;

    private FileVisitor fileVisitor;
    private String targetPath;

    public ListFileProducer(LinkedBlockingQueue<FileInfo> fileInfoQueue, String targetPath) {
        this.fileInfoQueue = fileInfoQueue;
        this.fileVisitor = new ListFileVisitor();
        this.targetPath = targetPath;
    }

    public void listFile() {
        try {
            Files.walkFileTree(Paths.get(targetPath), fileVisitor);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        listFile();
    }

    private class ListFileVisitor extends  SimpleFileVisitor<Path> {
        @SneakyThrows
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Objects.requireNonNull(file);
            Objects.requireNonNull(attrs);
            String suffix = FileNameUtil.getSuffix(file.toFile());
            FileInfo fileInfo = new FileInfo(suffix, file, file.getParent().toString(), file.getFileName().toString());
            // 当队列满时，会阻塞
            fileInfoQueue.put(fileInfo);
            return FileVisitResult.CONTINUE;
        }
    }
}
